"""
为缺少 profile 的用户补充创建 StudentProfile 或 TeacherProfile
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from dotenv import load_dotenv
load_dotenv()

from app import create_app
from app.extensions import db
from app.models.user import User, StudentProfile, TeacherProfile


def fix_missing_profiles():
    """修复缺少profile的用户"""
    app = create_app('development')
    
    with app.app_context():
        print("=" * 60)
        print("开始检查和修复缺少profile的用户")
        print("=" * 60)
        
        # 查找所有学生
        students = User.query.filter_by(role='student').all()
        print(f"\n共有 {len(students)} 个学生用户")
        
        students_fixed = 0
        for student in students:
            if not student.student_profile:
                print(f"✓ 为学生 {student.username} ({student.last_name}{student.first_name}) 创建 StudentProfile")
                profile = StudentProfile(
                    user_id=student.id,
                    student_id=student.username,
                    major=f'{student.department}',  # 使用系部作为专业
                    grade_level=1
                )
                db.session.add(profile)
                students_fixed += 1
        
        # 查找所有教师
        teachers = User.query.filter_by(role='teacher').all()
        print(f"\n共有 {len(teachers)} 个教师用户")
        
        teachers_fixed = 0
        for teacher in teachers:
            if not teacher.teacher_profile:
                print(f"✓ 为教师 {teacher.username} ({teacher.last_name}{teacher.first_name}) 创建 TeacherProfile")
                profile = TeacherProfile(
                    user_id=teacher.id,
                    employee_id=teacher.username,
                    department=teacher.department,
                    title='讲师'
                )
                db.session.add(profile)
                teachers_fixed += 1
        
        try:
            db.session.commit()
            print("\n" + "=" * 60)
            print(f"✅ 修复完成！")
            print(f"  - 学生 profile 创建: {students_fixed} 个")
            print(f"  - 教师 profile 创建: {teachers_fixed} 个")
            print("=" * 60)
        except Exception as e:
            db.session.rollback()
            print(f"\n❌ 修复失败: {str(e)}")
            raise


if __name__ == '__main__':
    fix_missing_profiles()


